import { Button, Card, Form, Input, Space, Image, message, Modal, Popconfirm } from 'antd';
import Table, { ColumnsType } from 'antd/es/table';
import { TableRowSelection } from 'antd/es/table/interface';
import { useState } from 'react';

import commonService from '@/api/services/commonService';
import { CartModal } from '@/components/CommonButtons/modal';
import { useCommon } from '@/hooks/common';
import setEditorDate from '@/pages/editor/setEditorDate';
import { useUserInfo } from '@/store/userStore';
import { toEditor } from '@/utils';
import AddBgModal from './AddBgModal/AddBgModal';
import addBgModalStore from './AddBgModal/addBgModalStore';

export default function DesignPage() {
  const uri = 'product';
  const cateName = '我的设计';
  const userInfo: any = useUserInfo();
  const {
    data = {},
    searchForm,
    onSearchFormReset,
    doDel,
    onSearch,
    handleChange,
    refetch,
  } = useCommon({ keyword: '' }, uri, {});

  const toMall = (row: any) => {
    commonService.getCustomApi('/member/product/applyToMall', { ids: row.id }).then(() => {
      message.success('发布成功');
      refetch();
    });
  };

  const [showModal, setShowModal] = useState(false);
  const [good, setGood] = useState<any>({});

  const handleShare = (row: any) => {
    commonService.getCustomApi('/member/t/GeneratingLink', { psi: row.id }).then((res) => {
      if (res) {
        navigator.clipboard.writeText(res).then(() => {
          Modal.info({
            title: '分享给好友',
            centered: true,
            content: (
              <div>
                <p>链接地址已保存在系统剪贴板中，您可以直接粘贴（Ctrl+V）</p>
                <Input defaultValue={res} readOnly />
              </div>
            ),
            okText: '关闭',
          });
        });
      }
    });
  };

  const toDesign = (row: any) => {
    toEditor(row);
  };

  const toAddCart = (row: any) => {
    setGood(row);
    setShowModal(true);
  };

  const columns: ColumnsType<any> = [
    {
      title: '产品',
      dataIndex: 'thumbs',
      width: 140,
      render: (thumbs: any, record: any) => {
        const img = JSON.parse(thumbs || '[]')[0];
        return (
          <div className="flex h-[120px]">
            <Image width={120} height={120} src={img} />
            <div className="ml-[10px]">
              <div className="text-left text-[16px] text-[#363A44]">{record.goodsName}</div>
              <div className="text-left text-[16px] text-[#686B73]">类目：{record.catalogueId}</div>
              <div className="text-left text-[16px] text-[#686B73]">编号：{record.id}</div>
              <div className="text-left text-[16px] text-[#686B73]">颜色：{record.color}</div>
              <div className="text-left text-[16px] text-[#686B73]">材质：{record.material}</div>
            </div>
          </div>
        );
      },
    },
    { title: '创建时间', dataIndex: 'createTime', align: 'center', width: 200 },
    {
      title: '操作',
      key: 'operation',
      align: 'center',
      width: 200,
      render: (_, record) => (
        <div className="flex items-center justify-center">
          {userInfo.userType == 2 ? (
            <Button className="mr-[20px] w-[112px]" type="primary" onClick={() => toMall(record)}>
              发布到商城
            </Button>
          ) : null}
          <div>
            <div>
              <Popconfirm
                title="确认删除该数据？"
                okText="确定"
                cancelText="取消"
                placement="left"
                onConfirm={() => doDel(record.id)}
              >
                <Button danger className="mr-[10px] w-[64px]">
                  删除
                </Button>
              </Popconfirm>
              <Button
                className="w-[112px]"
                type="primary"
                ghost
                onClick={() => {
                  window.location.href = `/#/editor/${record.id}`;
                  setEditorDate(record.ppId, record);
                }}
              >
                重新设计
              </Button>
            </div>
            <div className="mb-[10px] mt-[10px]">
              <Button className="mr-[10px] w-[64px]">下载</Button>
              <Button
                className="w-[112px]"
                type="primary"
                ghost
                onClick={() => {
                  const mockuplist = JSON.parse(record.previewThumbs || '[]');
                  addBgModalStore.setMockuplist(mockuplist);
                }}
              >
                添加背景
              </Button>
            </div>
            <div>
              <Button className="mr-[10px] w-[64px]" onClick={() => handleShare(record)}>
                分享
              </Button>
              <Button className="w-[112px]" type="primary" ghost onClick={() => toAddCart(record)}>
                加入购物车
              </Button>
            </div>
          </div>
        </div>
      ),
    },
  ];

  // rowSelection objects indicates the need for row selection
  const rowSelection: TableRowSelection<any> = {
    onChange: (selectedRowKeys, selectedRows) => {
      console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
    },
    onSelect: (record, selected, selectedRows) => {
      console.log(record, selected, selectedRows);
    },
    onSelectAll: (selected, selectedRows, changeRows) => {
      console.log(selected, selectedRows, changeRows);
    },
  };

  return (
    <Space direction="vertical" size="large" className="w-full">
      <Card title={cateName} bordered={false}>
        <Form layout="inline" form={searchForm} onFinish={onSearch}>
          <Form.Item name="keyword">
            <Input placeholder="产品名称或编号" />
          </Form.Item>
          <Form.Item>
            <Button type="primary" htmlType="submit">
              查询
            </Button>
          </Form.Item>
          <Form.Item>
            <Button onClick={onSearchFormReset}>重置</Button>
          </Form.Item>
        </Form>
        <div className="mt-[20px]">
          <Table
            rowKey="id"
            size="small"
            pagination={{ total: data.totalCount }}
            scroll={{ x: 'max-content' }}
            columns={columns}
            dataSource={data.list}
            rowSelection={{ ...rowSelection }}
            onChange={handleChange}
          />
        </div>
      </Card>
      <CartModal showModal={showModal} good={good} onClose={() => setShowModal(false)} />
      {/* 添加背景弹窗 */}
      <AddBgModal />
    </Space>
  );
}
